<!--
 * @Author: your name
 * @Date: 2021-09-02 08:57:28
 * @LastEditTime: 2024-06-26 14:52:51
 * @LastEditors: dh
 * @Description: In User Settings Edit
 * @FilePath: \A_demo\index.html
-->
<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>MutationObserver、IntersectionObserver、ResizeObserver</title>
	</head>
	<!--
	MutationObserver 创建一个观察器，提供了对监视DOM树更改的能力，是DOM3 Events规范的一部分
	IntersectionObserver 提供了一种异步观察目标元素与其祖先元素或顶级文档视窗(viewport)交叉状态的方法
	ResizeObserver 创建一个新的ResizeObserver对象监听元素大小变化
	三个使用方法相同
 -->
	<body>
		<div id="box">0</div>
		<script>
			// 选择需要观察变动的节点
			const targetNode = document.querySelector('#box');

			setInterval(() => {
				targetNode.textContent = +targetNode.textContent + 1;
			}, 1000);

			// 观察器的配置（需要观察什么变动）
			const config = {
				attributes: true,
				childList: true,
				subtree: true,
			};

			// 当观察到变动时执行的回调函数
			const callback = function (mutationsList, observer2222222) {
				// Use traditional 'for loops' for IE 11
				for (let mutation of mutationsList) {
					if (mutation.type === 'childList') {
						console.log('A child node has been added or removed.');
					} else if (mutation.type === 'attributes') {
						console.log('The ' + mutation.attributeName + ' attribute was modified.');
					}
				}
			};

			const observer = new MutationObserver(callback);

			observer.observe(targetNode, config);

			// 停止监听
			// observer.disconnect()
		</script>
	</body>
</html>
